import { useUserStoreHook } from "@/store/modules/user";
import type { Directive, DirectiveBinding } from "vue";

export const perms: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding<string | Array<string>>) {
    const { value } = binding;
    if (value) {
      !hasButtonPerms(value) && el.parentNode?.removeChild(el);
    } else {
      throw new Error(
        "[Directive: perms]: need perms! Like v-perms=\"['btn.add','btn.edit']\""
      );
    }
  }
};

/** 检查是否有按钮权限 */
function hasButtonPerms(value: string | Array<string>): boolean {
  if (!value) return false;
  
  const userStore = useUserStoreHook();
  const buttonPermissions = userStore.buttonPermissions;
  
  if (!buttonPermissions || buttonPermissions.length === 0) return false;
  
  // 支持通配符权限
  if (buttonPermissions.includes("*:*")) return true;
  
  if (typeof value === "string") {
    return buttonPermissions.includes(value);
  } else if (Array.isArray(value)) {
    return value.some(perm => buttonPermissions.includes(perm));
  }
  
  return false;
}
